package com.im.service.websocket.message;

import com.alibaba.fastjson2.JSON;
import com.im.service.common.constant.ImConstant;
import com.im.service.exception.BusinessException;
import com.im.service.infra.entity.ChatHistory;
import com.im.service.websocket.message.dto.SentMessage;
import com.im.service.websocket.message.enums.MessageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

import static com.im.service.exception.ErrorCode.INVALID_MESSAGE_FORMAT;

@Component
public class MessageProcessorFactory {
    @Autowired
    public List<MessageProcessor> messageProcessorList;

    /**
     * messageMetadata format: targetId:type:content
     * for example: bfce3943d6964c3ca0aaf14cc2abd5ee:DIRECT_MESSAGE:你好
     * @return
     */
    public Function<String, Mono<Void>> switchAndHandlerMessage(String senderId) {
        return messageMetadata -> {
            SentMessage sentMessage = JSON.parseObject(messageMetadata, SentMessage.class);

            MessageType messageType = MessageType.valueOf(sentMessage.getMessageType());

            MessageProcessor processor = messageProcessorList.stream()
                    .filter(it -> it.messageType() == messageType).findFirst()
                    .orElseThrow(() -> new BusinessException(INVALID_MESSAGE_FORMAT));
            return processor.process(senderId, sentMessage);
        };
    }
}
